<template>
  <div class="subject-content">

    <el-form :model="queryParams" size="medium" ref="queryForm" label-width="75px">
      <el-form-item label="文章名称" prop="articleName" size="mini">
        <el-input v-model="queryParams.articleName" clearable placeholder="请输入文章名称" @keyup.enter.native="searchQuery"></el-input>
      </el-form-item>

      <el-form-item label="分类" prop="classifyId" size="mini">
        <el-select v-model="queryParams.classifyId" placeholder="请选择分类" clearable>
          <el-option v-for="(item, index) in articleClassify" :key="index" :label="item.classifyName" :value="item.classifyId" :disabled="item.disabled"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="状态" prop="articleStatus" size="mini">
        <el-select v-model="queryParams.articleStatus" placeholder="请选择状态" clearable>
          <el-option v-for="(item, index) in dict.dictType.article_status" :key="index" :label="item.dictLabel" :value="item.dictValue"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item size="mini">
        <el-button type="primary" icon="el-icon-search" @click="searchQuery">提交</el-button>
        <el-button type="primary" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>


    <el-row :gutter="10" style="margin-bottom: 15px">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" @click="handleDelete" size="mini">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-refresh" @click="batchAdd" size="mini">批量添加</el-button>
      </el-col>
    </el-row>


    <el-table v-loading="loading" :data="articleList" border style="width: 100%;" :cell-style="{padding:'0'}" :row-style="{height:'10px'}"  @selection-change="handleSelectionChange">
      <el-table-column fixed="left" type="selection"       width="50" align="center"></el-table-column>
      <el-table-column prop="articleId"   label="ID"       width="180" fixed="left" sortable></el-table-column>
      <el-table-column prop="articleName" label="文章名称"   width="350"></el-table-column>
      <el-table-column label="文章缩略图"   align="center"   width="220">
        <template v-slot="scope">
          <img :src="img(scope.row.articleThumbnail)" style="height: 30%;width: 30%"/>
        </template>
      </el-table-column>
      <el-table-column label="主题色"      align="center" sortable>
        <template v-slot="scope">
          <el-color-picker disabled v-model="scope.row.imgColor"></el-color-picker>
        </template>
      </el-table-column>
      <el-table-column label="分类" align="center" sortable>
        <template v-slot="scope" label="分类" sortable>
          <a v-if="scope.row.lyClassify === null"></a>
          <a v-else v-text="scope.row.lyClassify.classifyName"></a>
        </template>
      </el-table-column>
      <el-table-column label="轮播图" align="center">
        <template v-slot="scope">
          <el-switch v-model="scope.row.isShuffling" active-value="1" inactive-value="0" @change="handleIsShufflingChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="推广" align="center">
        <template v-slot="scope">
          <el-switch v-model="scope.row.isPopularize" active-value="1" inactive-value="0" @change="handleIsPopularizeChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="状态"    align="center" sortable>
        <template v-slot="scope">
          <dictTag :options="dict.dictType.article_status" :value="scope.row.articleStatus"></dictTag>
        </template>
      </el-table-column>
      <el-table-column prop="updateDate" label="修改时间" align="center" width="160" sortable/><!--sortable 排序-->
      <el-table-column prop="createDate" label="创建时间" align="center" width="160" sortable/><!--sortable 排序-->
      <el-table-column fixed="right"     label="操作" width="130" align="center">
        <!-- 固定列需要使用fixed属性，它接受 Boolean 值或者left right，表示左边固定还是右边固定。 -->
        <template slot-scope="scope">
          <el-button type="text" size="small" icon="el-icon-edit" @click="rowUpdate(scope.row)">修改</el-button>
          <el-button type="text" size="small" icon="el-icon-delete" @click="rowDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <page
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.current"
        :limit.sync="queryParams.size"
        @pagination="getList"
    />

    <!-- 添加或修改 文章弹出框 -->
    <el-dialog :title="title" :visible.sync="open" width="1600px" append-to-body>
      <el-form ref="articleForm" :model="articleForm" :rules="rules" size="small" label-width="100px">
        <el-form-item label="文章名称" prop="articleName">
          <el-input v-model="articleForm.articleName" placeholder="请输入文章名称" clearable size="mini"></el-input>
        </el-form-item>
        <div></div>

        <el-form-item label="关键字" prop="articleKeyword">
          <el-input v-model="articleForm.articleKeyword" placeholder="请输入关键字" clearable size="mini"></el-input>
        </el-form-item>
        <div></div>

        <el-form-item label="描述" prop="articleDescription">
          <el-input v-model="articleForm.articleDescription" placeholder="请输入描述" clearable size="mini"></el-input>
        </el-form-item>
        <div></div>

        <el-form-item label="分类" prop="classifyId" size="mini">
          <el-select v-model="articleForm.classifyId" placeholder="请选择分类" clearable>
            <el-option v-for="(item, index) in articleClassify" :key="index" :label="item.classifyName" :value="item.classifyId" :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>
        <div></div>

        <el-form-item label="缩略图" prop="articleThumbnail" class="zkc_img">
          <el-upload
              ref="articleThumbnail"
              list-type="picture-card"
              limit:="1"
              accept="image/*"
              action="#"
              :http-request="requestUpload"
              :file-list="fileList"
              :auto-upload="true"
              :before-upload="avatarBeforeUpload"
              :on-change="onChangeUpload"
              :on-preview="handlePictureCardPreview">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <div></div>

        <el-form-item label="主题色" prop="imgColor">
          <el-color-picker v-model="articleForm.imgColor" size="small" show-alpha></el-color-picker>
          <div></div>
          <el-button type="primary" @click="getColor">主要按钮</el-button>
        </el-form-item>
        <div></div>

        <el-form-item label="轮播图" prop="isShuffling">
          <el-switch
              v-model="articleForm.isShuffling"
              active-color="#13ce66"
              active-value="1"
              inactive-value="0">
          </el-switch>
        </el-form-item>
        <div></div>

        <el-form-item label="推广" prop="isPopularize">
          <el-switch
              v-model="articleForm.isPopularize"
              active-color="#13ce66"
              active-value="1"
              inactive-value="0">
          </el-switch>
        </el-form-item>
        <div></div>

        <el-form-item label="状态" prop="articleStatus">
          <el-radio-group v-model="articleForm.articleStatus" size="medium">
            <el-radio v-for="(item, index) in dict.dictType.article_status" :key="index" :label="item.dictValue">
              {{ item.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="内容" >
          <div style="border: 1px solid #ccc;">
            <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editor"
                :defaultConfig="toolbarConfig"
                :mode="mode"
            />
            <Editor
                style="height: 500px; overflow-y: hidden;"
                v-model="html"
                :defaultConfig="editorConfig"
                :mode="mode"
                @onCreated="onCreated"
                @onChange="onChange"
            />
          </div>
        </el-form-item>
      </el-form>

      <div slot="footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>



    <!--  图片预览  -->
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" :alt="dialogImageName">
    </el-dialog>
  </div>






</template>

<script>

import {
  deleteArticleById,
  deleteArticleByIds,
  batchAdd,
  getArticleById,
  insertArticle,
  queryAllClassifyList,
  updateArticleId,
  handleIsShufflingChange,
  handleIsPopularizeChange,
  articleList
} from "@/api/admin/article";
import Page from "@/views/components/page";
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
// import { createEditor, createToolbar, IEditorConfig, IToolbarConfig,IDomEditor } from '@wangeditor/editor'
import ColorThief from 'colorthief'
import "@wangeditor/editor/dist/css/style.css"
import {upload} from "@/api/admin/common";
import {getToken} from '@/utils/cookie'
import dictTag from "@/views/components/dictTag";


export default {
  name: "Article",
  dicts:["article_status"],
  components: {Page,Editor,Toolbar,dictTag},
  data(){
    // 自定义校验图片
    const customCheckImageFn = (src, alt, url) => {
          if (!src) {
            this.$modal.msgWarning('图片网址不能为空！')
            return
          }
          if (src.indexOf('http') !== 0) {
            this.$modal.msgWarning('图片地址必须以 http/https 开头！')
            return '图片地址必须以 http/https 开头'
          }
          if(url.indexOf('http') !== 0) {
            this.$modal.msgWarning('图片链接必须以 http/https 开头')
            return '图片链接必须以 http/https 开头'
          }
          return true
          // 返回值有三种选择：
          // 1. 返回 true ，说明检查通过，编辑器将正常插入图片
          // 2. 返回一个字符串，说明检查未通过，编辑器会阻止插入。会 alert 出错误信息（即返回的字符串）
          // 3. 返回 undefined（即没有任何返回），说明检查未通过，编辑器会阻止插入。但不会提示任何信息
    }
    // 转换图片链接
    const customParseImageSrc = (src) => {
      if (src.indexOf('http') !== 0) {
        return "https://"+src;
      }
      return src
    }
    return{
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 是否显示弹出层
      open: false,
      // 弹出层标题
      title: "",
      // 选中数组
      ids: [],
      // 总条数
      total: 0,
      //表格数据
      articleList: [],
      // 查询参数  current 当前页   size 页大小
      queryParams: {
        current: 1,
        size: 10,
        articleName: undefined,
        articleStatus:undefined,
        classifyId: undefined,
      },

      // 添加、修改提交参数
      articleForm:{},

      //上传图片
      fileList:[],
      //图片二进制地址
      fileUrl:'',
      //上传图片(预览)(二进制地址)
      dialogImageUrl: '',
      dialogImageName:'',
      dialogVisible: false,

      //编辑器
      editor: null,
      // 文章内容
      html: '',
      mode: 'default', //  default  or simple
      toolbarConfig: { },
      // 编辑器配置
      editorConfig: {
        placeholder: '请输入文章内容...',
        MENU_CONF: {
          // // 字体大小
          // fontSize:{
          //   fontSizeList:['28px']
          // },
          // // 字体
          // fontFamily:{
          //   fontFamilyList:['黑体']
          // },
          // 表情
          emotion:{
            emotions: '😀 😃 😄 😁 😆 😅 🤣 😂 🙂 🙃 😉 😊 😇 🥰 😍 🤩 😘 😗 ☺ 😚 😙 🥲 😋 😛 😜 🤪 😝 🤑 🤗 🤭 🤫 🤔 🤐 🤨 😐 😑 😶 😏 😒 🙄 😬 🤥 😌 😔 😪 🤤 😴 😷 🤒 🤕 🤢 🤮 🤧 🥵 🥶 🥴 😵 🤯 🤠 🥳 🥸 😎 🤓 🧐 😕 😟 🙁 ☹ 😮 😯 😲 😳 🥺 😦 😧 😨 😰 😥 😢 😭 😱 😖 😣 😞 😓 😩 😫 🥱 😤 😡 😠 🤬 😈 👿 💀 ☠ * 🤡 👹 👺 👻 👽 👾 🤖 😺 😸 😹 😻 😼 😽 🙀 😿 😾 🙈 🙉 🙊 💋 💌 💘 💝 💖 💗 💓 💞 💕 💟 ❣ 💔 ❤ 🧡 💛 💚 💙 💜 🤎 🖤 🤍 💯 💢 💥 💫 💦 💨 🕳 💣 💬 👁‍🗨 🗨 🗯 💭 💤'.split(' ') // 数组
          },
          // 插入网络图片的校验
          insertImage:{
            //  插入图片之后的回调
            onInsertedImage(imageNode) {
              if (imageNode == null) return
              const { src, alt, url, href } = imageNode
              console.log('inserted image', src, alt, url, href)
            },
            // 校验图片链接
            checkImage: customCheckImageFn, // 也支持 async 函数
            // 转换图片链接
            parseImageSrc: customParseImageSrc, // 也支持 async 函数
          },

          // 编辑网络图片的校验
          editImage: {
            // 更新图片之后的回调
            onUpdatedImage(imageNode = null) {
              if (imageNode == null) return
              const { src, alt, url } = imageNode
              console.log('updated image', src, alt, url)
            },
            // 校验图片链接
            checkImage: customCheckImageFn, // 也支持 async 函数
            // 转换图片链接
            parseImageSrc: customParseImageSrc, // 也支持 async 函数
          },

          //图片上传
          uploadImage:{
            server:process.env.VUE_APP_BASE_API+'/common/editorFile',
            fieldName:"file",
            // 最多可上传几个文件，默认为 100
            maxNumberOfFiles: 10,
            // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
            allowedFileTypes: ['image/*'],
            // 自定义增加 http  header
            headers: {
              Authorization: getToken(),
            },
            // 跨域是否传递 cookie ，默认为 false
            withCredentials: true,
            // 超时时间，默认为 10 秒
            timeout: 5 * 1000, // 5 秒

            // 上传之前触发
            onBeforeUpload(file) {
              console.log("上传之前触发")
              // file 选中的文件，格式如 { key: file }
              return file
              // 可以 return
              // 1. return file 或者 new 一个 file ，接下来将上传
              // 2. return false ，不上传这个 file
            },
            // 上传进度的回调函数
            onProgress(progress) {
              console.log("上传进度的回调函数")
              // progress 是 0-100 的数字
              console.log('progress', progress)
            },
            // 单个文件上传成功之后
            onSuccess(file, res) {
              console.log("单个文件上传成功之后")
              console.log(file, res)
            },
            // 单个文件上传失败
            onFailed(file, res) {
              console.log("单个文件上传失败")
              console.log(file, res)
            },
            // 上传错误，或者触发 timeout 超时
            onError(file, err, res) {
              console.log("上传错误，或者触发 timeout 超时")
              console.log(file, err, res)
            },
            // 自定义插入
            async customInsert(result, insertFn) {
              // 从 result 中找到 url alt href ，然后插图图片
              insertFn(  /*代码中参数顺序  src, alt, url, href */
                  location.protocol+'//' +location.host+process.env.VUE_APP_BASE_API+result.data.url,
                  result.data.alt,
                  location.protocol+'//' +location.host+process.env.VUE_APP_BASE_API+result.data.url,
                  location.protocol+'//' +location.host+process.env.VUE_APP_BASE_API+result.data.href
              )
            },
          },
        },

      },
      //分类
      articleClassify:[],
      // 表单数据校验
      rules: {
        articleName: [{
          required: true,
          message: '请输入角色名称',
          trigger: 'blur'
        }],

        classifyId:[{
          required: true,
          message: '请选择分类',
          trigger: 'blur'
        }]
      },

    }
  },
  methods:{
    /**获取全部文章*/
    getList(){
      articleList(this.queryParams).then(res => {
        this.articleList = res.data.records;
        this.total = res.data.total;
        this.loading = false;
      })
    },
    /** 分类下拉数据 */
    queryAllClassifyList(){
      queryAllClassifyList().then(res =>{
        this.articleClassify=res.data
      })
    },
    /** 搜索按钮操作 */
    searchQuery() {
      this.queryParams.current = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.searchQuery();
    },
    /** 表单重置 */
    reset() {
      this.articleForm = {
        articleId: undefined,
        articleName: undefined,
        articleKeyword: undefined,
        articleDescription: undefined,
        articleThumbnail: undefined,
        imgColor: undefined,
        articleContent: undefined,
        articleStatus: undefined,
        isShuffling: undefined,
        isPopularize:undefined,
        classifyId: undefined,
      };
      this.resetForm("articleForm");
    },
    /** 头工具栏--添加*/
    handleAdd(){
      this.reset();
      this.title = "添加文章"
      this.html=undefined
      this.articleForm.articleThumbnail="/ly/ly-images/文章.png"
      this.articleForm.imgColor="rgba(255, 0, 0, 0)"
      this.articleForm.isShuffling="1"
      this.articleForm.articleStatus="1"
      this.fileList=[{url:require('/ly/ly-images/文章.png')}]
      this.open = true
    },
    /** 头工具栏--修改 */
    handleUpdate(){
      if (this.ids.length === 0) {
        this.$modal.msgWarning('请选择要修改的文章！')
      }else if(this.ids.length >1){
        this.$modal.msgWarning('请选择一个文章进行修改！')
      }else{
        this.reset();
        this.html=undefined;
        const articleIds = this.ids
        getArticleById(articleIds).then(res =>{
          this.articleForm = res.data;
          this.fileList = [{url:process.env.VUE_APP_BASE_API+res.data.articleThumbnail}]
          this.html = res.data.articleContent
          this.title = "修改文章";
          this.open = true;
        })
      }
    },
    /** 头工具栏--删除*/
    handleDelete(){
      const data = this.ids
      this.$modal.confirm('是否确认删除？').then(function () {
        return deleteArticleByIds(data)
      }).then(res => {
        this.getList()
        this.$modal.msgSuccess(res.msg);
      });
    },
    /** 头工具栏--批量添加 */
    batchAdd(){
      this.$modal.confirm('是否批量添加数据？').then(function () {
        return batchAdd()
      }).then(res => {
        this.$modal.msgSuccess(res.msg);
      });
    },
    /**取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["articleForm"].validate(valid => {
        if(valid){
          if(this.articleForm.articleId!=undefined){
            updateArticleId(this.articleForm).then(res =>{
              this.$modal.msgSuccess(res.msg);
              this.open = false;
              this.getList()
            })
          }else{
            insertArticle(this.articleForm).then(res =>{
              this.$modal.msgSuccess(res.msg);
              this.open = false;
              this.getList()
            })
          }
        }
      });
    },
    /**行工具--修改 */
    rowUpdate(row){
      this.reset();
      const articleId = row.articleId
      getArticleById(articleId).then(res =>{
        this.articleForm = res.data;
        this.fileList = [{url:process.env.VUE_APP_BASE_API+res.data.articleThumbnail}]
        this.html = res.data.articleContent
        this.title = "修改用户";
        this.open = true;
      })
    },
    /**行工具--删除 */
    rowDelete(row){
      const articleId = row.articleId
      this.$modal.confirm('是否确认删除？').then(function () {
        return deleteArticleById(articleId)
      }).then(res => {
        this.getList()
        this.$modal.msgSuccess(res.msg);
      });
    },

    // 修改轮播状态
    handleIsShufflingChange(row){
      let text = row.isShuffling === "1" ? "轮播启用" : "轮播停用";
      this.$modal.confirm("确认要"+text+row.articleName+"角色吗？").then(function (){
        return handleIsShufflingChange(row.articleId,row.isShuffling);
      }).then(res =>{
        this.$modal.msgSuccess(text + res.msg);
      }).catch(function() {
        row.isShuffling = row.isShuffling === "0" ? "1" : "0";
      });
    },

    // 修改推广状态
    handleIsPopularizeChange(row){
      let text = row.isPopularize === "1" ? "推广启用" : "推广停用";
      this.$modal.confirm("确认要"+text+row.articleName+"角色吗？").then(function (){
        return handleIsPopularizeChange(row.articleId,row.isPopularize);
      }).then(res =>{
        this.$modal.msgSuccess(text + res.msg);
      }).catch(function() {
        row.isPopularize = row.isPopularize === "0" ? "1" : "0";
      });
    },


    /** 编辑器创建完毕时的回调函数。*/
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
    /** 编辑器内容、选区变化时的回调函数。*/
    onChange(editor){
      this.articleForm.articleContent=undefined
      this.articleForm.articleContent=editor.getHtml()
    },
    /** 自定义图片上传接口*/
    requestUpload(obj){
      let formData = new FormData();
      formData.append("file", obj.file);
      upload(formData).then(res=>{
        this.articleForm.articleThumbnail = res.data
        this.$modal.msgSuccess(res.msg);
        let docImg= document.createElement("img")
        docImg.src=this.fileUrl
        let colorthief = new ColorThief();
        let color= colorthief.getColor(docImg)
        this.articleForm.imgColor="rgba("+color[0]+","+color[1]+","+color[2]+")"
      })
    },
    /** 表单提交 图片大小 格式验证*/
    avatarBeforeUpload(file) {
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        this.$message.error('上传头像图片大小不能超过 5MB!');
      }
      return isLt5M;
    },
    /** 图片状态改变时触发(只上传一张图片，上传第二张时会覆盖第一张图片)*/
    onChangeUpload(res, file) {
      if (file.length > 1) {
        file.splice(0, 1);  //在位置 0，删除 1 个项目：
      }
      this.fileUrl=res.url
    },
    /** 点击文件列表中已上传的文件时的钩子(预览) */
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogImageName = file.name;
      this.dialogVisible = true;
    },
    /** 获取图片主题（颜色）*/
    getColor(){
      let docImg= document.querySelector(".el-upload-list li img")
      let colorthief = new ColorThief();
      let color= colorthief.getColor(docImg)
      this.articleForm.imgColor="rgba("+color[0]+","+color[1]+","+color[2]+")"
    },
    /**多选框选中数据*/
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.articleId)
    },
    /** 路径拼接 */
    img(url) {
      return process.env.VUE_APP_BASE_API + url
    },
  },
  mounted() {

  },
  created(){// 初始化
    this.getList()
    this.queryAllClassifyList();
  }
}
</script>

<style scoped>
.el-row {
  display: inline-block;
}
.el-form-item {
  display: inline-block;
}
/*/deep/ .el-upload-list li{*/
/*   width: 50%;*/
/*   height: 50%;*/
/*}*/

/deep/ .w-e-panel-content-emotion{
  width: 600px;
}
</style>
